package com.example.zhilongzhang.constructionpayapp.adapter;

import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.example.zhilongzhang.constructionpayapp.R;

import com.example.zhilongzhang.constructionpayapp.bean.MeXYBean;
import com.example.zhilongzhang.constructionpayapp.bean.StatBean;
import com.example.zhilongzhang.constructionpayapp.method.DayAxisValueFormatter;
import com.example.zhilongzhang.constructionpayapp.method.MyValueFormatter;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class StatAdapter extends PagerAdapter {
    Context mContext;
    List<MeXYBean> mData;
    PieChart pieChart;
    public String strX = "日";
    public int type = 0;

    public StatAdapter(Context context, List<MeXYBean> list) {
        mContext = context;
        mData = list;
    }

    @Override
    public int getCount() {
        return 2;
    }

    BarChart chart;

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        switch (position) {
            case 1:
                View view = View.inflate(mContext, R.layout.item_stat_circular, null);
                pieChart = view.findViewById(R.id.piechart);
                setPieChart();
                container.addView(view);
                return view;
            default:
                View view1 = View.inflate(mContext, R.layout.item_stat_rect, null);
                chart = view1.findViewById(R.id.barChart);
                setRectChart();
                container.addView(view1);
                return view1;
        }
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // super.destroyItem(container,position,object); 这一句要删除，否则报错
        container.removeView((View) object);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    private void setRectChart() {
        chart.setDrawBarShadow(false);
        chart.setDrawValueAboveBar(true);
        chart.setMaxVisibleValueCount(30);
        chart.getDescription().setEnabled(false);
        chart.setPinchZoom(false);
        chart.setDrawBarShadow(false);
        chart.setDrawGridBackground(false);
        //右侧是否显示Y轴数值
        chart.getAxisRight().setDrawLabels(false);
        chart.getAxisLeft().setDrawGridLines(false);
        chart.animateY(1500);
//        chart.getXAxis().setLabelsToSkip(4);

        chart.setScaleMinima(5f,1f);
        chart.setScaleEnabled(false);
        chart.getLegend().setEnabled(false);

        setY();
        setX();
        initChar();
    }

    private void setY() {
        ValueFormatter custom = new MyValueFormatter("元");
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setAxisMinimum(0);
        leftAxis.setValueFormatter(custom);
    }

    private void setX() {
        ValueFormatter custom = new DayAxisValueFormatter(chart, strX);
        XAxis xAxis = chart.getXAxis();
        xAxis.setAxisMinimum(0);
        xAxis.setValueFormatter(custom);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
    }
    private void initChar() {
        ArrayList<BarEntry> values = new ArrayList<>();
        for (int i = 0; i < mData.size(); i++) {
           // Log.e("tongjie","X="+mData.get(i).getStatX()+"  Y="+(new BigDecimal(mData.get(i).getStatY()).setScale(2,BigDecimal.ROUND_HALF_UP).floatValue()));
            values.add(new BarEntry(mData.get(i).getStatX(), mData.get(i).getStatY()));
        }
        BarDataSet set1;
        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) chart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(values, "聚合宝");
            set1.setColors(ColorTemplate.VORDIPLOM_COLORS);
            set1.setDrawIcons(false);
            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1);
            BarData data = new BarData(dataSets);
            chart.setData(data);
            chart.setFitBars(true);
        }

        chart.invalidate();
    }

    private void setPieChart() {
        pieChart.setUsePercentValues(true);
        pieChart.getDescription().setEnabled(false);
        pieChart.setExtraOffsets(5, 10, 5, 5);

        pieChart.setDragDecelerationFrictionCoef(0.95f);

        pieChart.setCenterText(generateCenterSpannableText());

        pieChart.setExtraOffsets(20.f, 0.f, 20.f, 0.f);

        pieChart.setDrawHoleEnabled(true);
        pieChart.setHoleColor(Color.WHITE);

        pieChart.setTransparentCircleColor(Color.WHITE);
        pieChart.setTransparentCircleAlpha(110);

        pieChart.setHoleRadius(58f);
        pieChart.setTransparentCircleRadius(61f);

        pieChart.setDrawCenterText(true);

        pieChart.setRotationAngle(0);
        // enable rotation of the chart by touch
        pieChart.setRotationEnabled(true);
        pieChart.setHighlightPerTapEnabled(true);

        // chart.setUnit(" €");
        // chart.setDrawUnitsInChart(true);

        // add a selection listener
        pieChart.animateY(1400, Easing.EaseInOutQuad);
        // chart.spin(2000, 0, 360);

        Legend l = pieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setEnabled(false);
        setData(mData.size(), 100);
    }

    private SpannableString generateCenterSpannableText() {

        SpannableString s = new SpannableString("聚合宝");

        s.setSpan(new ForegroundColorSpan(Color.parseColor("#0099EE")), 0, s.length(), 0);
        s.setSpan(new RelativeSizeSpan(3f), 0, s.length(), 0);
        return s;
    }

    private void setData(int count, float range) {

        ArrayList<PieEntry> entries = new ArrayList<>();

        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        for (int i = 0; i < count; i++) {
            entries.add(new PieEntry((mData.get(i).getStatY()), mData.get(i).getStatX() + strX));
        }

        PieDataSet dataSet = new PieDataSet(entries, "");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);


        dataSet.setValueLinePart1OffsetPercentage(80.f);
        dataSet.setValueLinePart1Length(0.2f);
        dataSet.setValueLinePart2Length(0.4f);
        //dataSet.setUsingSliceColorAsValueLineColor(true);

        //dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.BLACK);
        pieChart.setData(data);

        // undo all highlights
        pieChart.highlightValues(null);

        pieChart.invalidate();
    }

    public void setNotify(List<MeXYBean> list) {
        this.mData=list;
        switch (type) {
            case 1:
                Log.e("shujv222", "幸运星1111=" + mData.size());
                setData(mData.size(), 100);
                break;
            default:
                Log.e("shujv222", "幸运星=" + mData.size());
                initChar();
                break;
        }

    }
}
